<template>
  <div v-if="authStore.isAuthenticated" class="member-management-container">
    <h2>Adult Member Management</h2>
    <a-alert v-if="error" type="error">{{ error }}</a-alert>
    <a-spin :spinning="loading">
      <a-table :columns="columns" :data-source="members" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'actions'">
            <a-popconfirm title="Are you sure delete this member?" ok-text="Yes" cancel-text="No"
              @confirm="showConfirm(record.userId)" @cancel="cancel">
              <a href="#" style="color: red;">Delete</a>
            </a-popconfirm>
          </template>
          <template v-else-if="column.key === 'birthDate'">
            {{ formatDate(record.birthDate) }}
          </template>
        </template>
      </a-table>
    </a-spin>
  </div>
  <a-alert v-else class="no-data" type="warning" show-icon>
    <template #message>
      You must log in/register to manage members.
    </template>
    <template #description>
      Redirecting to the login page in {{ countdown }} seconds...
    </template>
  </a-alert>
  <a-modal
    v-model:visible="confirmVisible"
    title="Delete Confirmation"
    ok-text="Confirm Delete"
    cancel-text="Cancel"
    @ok="handleDelete"
  >
    <p>Are you sure you want to delete the information of user ID {{ currentUserId }}?</p>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';
import { Modal } from 'ant-design-vue'; // 或者使用组件式引入
import axios from '../axios';
import dayjs from 'dayjs';

// 定义 Member 接口
interface Member {
  userId: number;
  sruNumber: string;
  address: string;
  birthDate: string;
  phoneNumber: string;
  mobileNumber: string;
  zipCode: string;
  email: string;
  closest: string;
  closestPhoneNumber: string;
  doctor: string;
  doctorPhoneNumber: string;
  knownHealthIssues: string;
}

const authStore = useAuthStore();
const router = useRouter();
const members = ref<Member[]>([]);
const loading = ref(false);
const error = ref('');
const countdown = ref(5);
const confirmVisible = ref(false);
const currentUserId = ref(0);
// 表格列定义
const columns = [
  { title: 'User ID', dataIndex: 'userId', key: 'userId' },
  { title: 'SRU Number', dataIndex: 'sruNumber', key: 'sruNumber' },
  { title: 'Address', dataIndex: 'address', key: 'address' },
  { title: 'Birth Date', dataIndex: 'birthDate', key: 'birthDate' },
  { title: 'Phone Number', dataIndex: 'phoneNumber', key: 'phoneNumber' },
  { title: 'Mobile Number', dataIndex: 'mobileNumber', key: 'mobileNumber' },
  { title: 'Zip Code', dataIndex: 'zipCode', key: 'zipCode' },
  { title: 'Email', dataIndex: 'email', key: 'email' },
  { title: 'Closest Contact', dataIndex: 'closest', key: 'closest' },
  { title: 'Closest Contact Phone', dataIndex: 'closestPhoneNumber', key: 'closestPhoneNumber' },
  { title: 'Doctor Name', dataIndex: 'doctor', key: 'doctor' },
  { title: 'Doctor Phone', dataIndex: 'doctorPhoneNumber', key: 'doctorPhoneNumber' },
  { title: 'Health Issues', dataIndex: 'knownHealthIssues', key: 'knownHealthIssues' },
  { title: 'Actions', key: 'actions' },
];

// 格式化日期
const formatDate = (dateString: string) => {
  return dayjs(dateString).format('YYYY-MM-DD');
};
const cancel = (e: MouseEvent) => {
  console.log(e);
};
// 获取会员列表
const fetchMembers = async () => {
  try {
    loading.value = true;
    const res = await axios.get('/members');
    members.value = res.data.data; // 根据 API 响应结构调整
  } catch (err) {
    error.value = 'Failed to fetch member information';
  } finally {
    loading.value = false;
  }
};

const showConfirm = (userId: number) => {
  currentUserId.value = userId;
  confirmVisible.value = true;
};
// 删除会员
const handleDelete = async () => {
  try {
    await axios.delete(`/members/${currentUserId.value}`);
    fetchMembers();
    currentUserId.value = 0;
  } catch (err) {
    error.value = 'Failed to delete member';
  } finally {
    confirmVisible.value = false;
  }
};

// 监听未登录状态，启动倒计时
watch(() => authStore.isAuthenticated, (isAuthenticated) => {
  if (!isAuthenticated) {
    const timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(timer);
        router.push({ name: 'Auth' });
      }
    }, 1000);
  }
}, { immediate: true });

// 页面加载时获取数据
onMounted(() => {
  if (authStore.isAuthenticated) {
    fetchMembers();
  }
});
</script>

<style scoped>
.member-management-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}
</style>